<template>
    <div class="feature_wrap">
        <el-row v-if="hideTop != true" type="flex" align="middle" style="margin-bottom:10px">
            在 <el-select v-model="scene" multiple collapse-tags size="small" style="margin:0 8px;" placeholder="请选择" @change="changeWhere">
                <el-option v-for="behavior in scenes" :key="behavior.id" :label="behavior.label"
                    :value="behavior.id">
                </el-option>
            </el-select><span style="color: #888;padding-right: 3px;">(可多选)</span>中，选择用户
            <el-select style="margin:0 8px; width: 90px;" v-model="day" placeholder="请选择" size="small" @change="changeWhere">
                <el-option v-for="daytime in days" :key="daytime.id" :label="daytime.label" :value="daytime.id">
                </el-option>
            </el-select>内发生的行为：
        </el-row>
        <el-row type="flex" align="middle" ref="scrollBox" v-loading="fullLoading">
            <div class="retarget-left" style="width: 432px;">
                <div class="logic-tilte">
                    <span @click="cutlogic=1" :class="{active:cutlogic==1}">添加类目词
                    </span>
                    <span @click="cutlogic=2" :class="{active:cutlogic==2}">添加关键词
                    </span>
                </div>
                <div class="tab-content">
                    <div v-show="cutlogic==1" style="margin-top: 15px;">
                        <el-autocomplete class="inline-input" v-model="prologic_search" :fetch-suggestions="querySearch"
                            placeholder="请输入行为类目词" :trigger-on-focus="false" @select="handleSelect">
                            <i class="el-icon-edit el-input__icon" slot="suffix" @click="handleIconClick">
                            </i>
                            <template slot-scope="{ item }">
                                <div class="name">{{ item.name }}</div>
                                <span class="addr">{{ item.num }}</span>
                            </template>
                        </el-autocomplete>
                        <!-- <el-input placeholder="请输入行为类目词" size="small" v-model="prologic_search"
                            class="input-with-select" style="width: 410px;">
                            <el-button slot="append" icon="el-icon-search">
                            </el-button>
                        </el-input> -->
                        <el-row type="flex" align="middle" class="overflow_wrap"  id="scrollBox">
                            <div v-for="i in groups.length" :key="i" class="select-panel-left">
                                <span class="header-title">{{getName(i)}}</span>
                                <ul>
                                    <li>
                                        <el-checkbox v-model="isAllSelect" :indeterminate="isIndeterminate(categorys[i-1])" @change="selectAll(i, $event)">全选</el-checkbox>
                                    </li>
                                    <el-checkbox-group v-model="selectedIds">
                                        <li v-for="category in categorys[i-1]" :key="category.id">
                                            <el-row type="flex" align="middle">
                                                <el-checkbox :label="category.id"
                                                    @change="selectCate($event, category, false)" class="check_none"></el-checkbox>
                                                <el-row class="check_contact" type="flex" align="middle"
                                                    justify="space-between">
                                                    <el-button type="text" @click="clickCategory(i, category.id)">
                                                        <el-tooltip placement="top">
                                                            <div slot="content">{{category.name}}覆盖人数{{category.num}}
                                                            </div>
                                                            <div>{{category.name}}</div>
                                                        </el-tooltip>
                                                        <i v-if="category.children" class="el-icon-arrow-right"></i>
                                                    </el-button>
                                                </el-row>
                                            </el-row>
                                        </li>
                                    </el-checkbox-group>
                                </ul>
                            </div>
                        </el-row>
                        <!-- <div class="correlation-word">
                            <el-row type="flex" justify="space-between">
                                <div class="name">金融相关词：</div>
                                <el-button type="text" size="mini">更多<i class="el-icon-arrow-right"></i></el-button>
                            </el-row>
                            <div class="words">
                                <el-tooltip v-for="word in words" :key="word.id" placement="top">
                                    <div slot="content">{{word.prompt}}</div>
                                    <el-button type="text" size="mini">+{{word.name}}</el-button>
                                </el-tooltip>
                            </div>
                        </div> -->
                    </div>
                    <div v-show="cutlogic==2" style="margin-top: 15px;" v-loading="loading">
                        <el-autocomplete class="inline-input" v-model="prologic_search2"
                            :fetch-suggestions="querySearch2" placeholder="请输入行为类目词或关键词" :trigger-on-focus="false"
                            @select="handleSelect">
                            <i class="el-icon-edit el-input__icon" slot="suffix" @click="handleIconClick">
                            </i>
                            <template slot-scope="{ item }">
                                <div class="name">{{ item.name }}</div>
                                <span class="addr">{{ item.num }}</span>
                            </template>
                        </el-autocomplete>

                        <!-- <el-input placeholder="请输入行为类目词或关键词" size="small" v-model="prologic_search"
                            class="input-with-select" style="width: 410px;">
                            <el-button slot="append" icon="el-icon-search">
                            </el-button>
                        </el-input> -->
                        <el-row type="flex" align="middle">
                            <div class="select-panel-left" style="width: 100%;">
                                <span class="header-title">{{keywordTitle}}</span>
                                <ul class="key-item">
                                    <li v-for="item in keywords" :key="item.id">
                                        <el-row type="flex" align="middle" justify="space-between">
                                            <span>{{item.name}}</span>
                                            <span>{{item.num}}</span>
                                            <span>
                                                <el-button @click="addKeyword(item)" type="text">添加
                                                </el-button>
                                            </span>
                                            <span>
                                                <el-button  type="text">查关键词
                                                </el-button>
                                            </span>
                                        </el-row>
                                    </li>

                                </ul>
                            </div>
                        </el-row>
                        <div class="correlation-word">
                            <span>
                                <el-button style="padding: 3px 0 0 3px;" type="text">
                                    添加全部“{{keywordTitle}}”相关关键词</el-button>
                            </span>
                        </div>
                    </div>
                </div>
            </div>
            <i class="el-icon-d-arrow-right"></i>
            <div class="select-panel-left retarget-right feature-right">
                <span class="words-title">
                    <el-row type="flex" justify="space-between">
                        还可添加行为： {{total}} 个<el-button @click="clear" style="padding: 0;" type="text">清空
                        </el-button>
                    </el-row>
                    <el-row type="flex" class="word-num">
                        <span>类目词：{{count_category}}</span>
                        <span>关键词：{{count_keyword}}</span>
                    </el-row>
                </span>
                <el-row type="flex" align="middle" class="panel-screen">
                    <el-dropdown @command="handleDropdown" class="header-select" trigger="click">
                        <span class="el-dropdown-link">
                            {{dropdownTitle}}<i class="el-icon-arrow-down el-icon--right"></i>
                        </span>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="0">全部</el-dropdown-item>
                            <el-dropdown-item command="1">类目词</el-dropdown-item>
                            <el-dropdown-item command="2">关键词</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                    <div class="header-cover">覆盖人数</div>
                </el-row>
                <ul>
                    <li class="feature-select" v-for="item in selectedFilter" :key="item.id"
                        @mouseover="item.show=true">
                        <el-row type="flex" align="middle">
                            <div class="feature-name">{{item.name}}</div>
                            <div class="feature-num">{{item.num}}</div>
                            <el-row type="flex" class="operate">
                                <el-button @click="del(item)" size="small" type="text">删除</el-button>
                                <el-button @click="keywordSearch(item.id)" size="small" type="text">查关键词</el-button>
                            </el-row>
                        </el-row>
                    </li>
                </ul>
                <!-- <el-row type="flex" align="middle" class="auto-select-word">
                    <el-button type="text">使用自动选词</el-button>
                    <el-tooltip content="系统根据行为定向所有已选结果，自动推荐词包" placement="top">
                        <i class="el-icon-question" style="color:#409EFF;"></i>
                    </el-tooltip>
                </el-row> -->
            </div>
        </el-row>
    </div>
</template>

<script>
const CATEGORY = 'CATEGORY'
const KEYWORD = 'KEYWORD'
    export default {
        name: 'FeaturePicker',
        model: {
            prop: 'actionObj',
            event: 'change',
        },
        props: ['hideTop', 'actionObj'],
        data() {
            return {
                loading: false,
                fullLoading: false,
                advertiser_id: 0,
                categoryData: [],
                categoryList: [],
                prologic_search: '',
                prologic_search2: '',
                dropdownType: '',
                scene: [],
                day: 7,
                groups: [0],
                keywords: [],
                selected: [],
                isAllSelect: [false, false, false, false],
                keywordTitle: '',
                dropdownTitle: '全部',
                // behavior: [],
                scenes: [{
                    id: 'E-COMMERCE',
                    label: '电商互动行为'
                }, {
                    id: 'NEWS',
                    label: '资讯互动行为'
                }, {
                    id: 'APP',
                    label: 'APP推广互动行为'
                }],
                // behavTime: [],
                days: [{
                    id: '7',
                    label: '7天'
                }, {
                    id: '15',
                    label: '15天'
                }, {
                    id: '30',
                    label: '30天'
                }, {
                    id: '60',
                    label: '60天'
                }, {
                    id: '90',
                    label: '90天'
                }, {
                    id: '180',
                    label: '180天'
                }, {
                    id: '365',
                    label: '365天'
                }],
                cutlogic: 1,
                // selectedFilter: [],
            }
        },
        watch: {
            actionObj: {
                immediate: true, // 很重要！！！
                handler() {
                    if (this.actionObj) {
                        console.log('actionObj', this.actionObj)
                        this.advertiser_id = this.actionObj.advertiser_id
                        this.scene = this.actionObj.scene
                        this.day = this.actionObj.days
                        if (this.actionObj.categories && !Array.isArray(this.actionObj.categories)) {
                            this.actionObj.categories = JSON.parse(this.actionObj.categories)
                        }
                        if (this.actionObj.words && !Array.isArray(this.actionObj.words)) {
                            this.actionObj.words = JSON.parse(this.actionObj.words)
                        }
                        this.setDefault()
                    }
                }
            }
        },
        created() {
            
        },
        computed: {
            categorys: {
                get: function () {
                    let cat = []
                    cat.push(this.categoryData)
                    for (let i = 1; i < this.groups.length; i++) {
                        const id = this.groups[i];
                        let c = this.getCategory(id)
                        if (c && c.children) {
                            cat.push(c.children)
                        }
                    }
                    // console.log('categoryData', cat)
                    return cat
                }
            },
            selectedIds: {
                get: function() {
                    let ids = []
                    this.selected.forEach(ele => {
                        ids.push(ele.id)
                    })
                    // console.log(this.selected, 'ids', ids.join(','))
                    return ids
                },
                set: function(ids) {
                    ids.forEach(id => {
                        if (this.selected.findIndex( e => e.id == id && e.type=='CATEGORY') == -1) {
                            let cate = this.categoryData.find(e2 => e2.id == id)
                            if (cate) {
                                this.selected.push(cate)
                            }
                        }
                    })
                    // console.log(ids, this.selected)
                }
            },
            selectedFilter: {
                get: function () {
                    return this.getTopSelects(this.dropdownType)
                }
            },
            total: {
                get: function () {
                    let maxTotal = 350
                    return maxTotal - this.selectedFilter.length
                }
            },
            count_category: {
                get: function() {
                    let data = this.getTopSelects(CATEGORY)
                    let count = 0
                    data.forEach(ele => {
                        if (ele.type == CATEGORY) {
                            count++
                        }
                    })
                    return count
                }
            },
            count_keyword: {
                get: function() {
                    let data = this.getTopSelects(KEYWORD)
                    let count = 0
                    data.forEach(ele => {
                        if (ele.type == KEYWORD) {
                            count++
                        }
                    })
                    return count
                }
            },
            // isAllSelect: {
            //     get: function(i, b, c) {
            //         console.log('====', i, b, c)
            //         let ret = true
            //         let data = this.getTopSelects('类目词')
            //         for (let i = 0; i < this.categoryData.length; i++) {
            //             const cate = this.categoryData[i];
            //             if (data.findIndex(e => e.id == cate.id) == -1) {
            //                 ret = false
            //                 break
            //             }
            //         }
            //         // console.log(data)
            //         return ret
            //     },
            //     set: function() {
            //     }
            // }
        },
        mounted() {
            this.loadData()
        },
        // updated: function() {
        //     console.log('update')
        //     this.$nextTick(function() {
        //         this.$el.querySelector('#scrollBox').scrollLeft = 500
        //     });
        // },
        methods: {
            loadData() {
                let scene = this.scene
                if (scene.length == 0) {
                    scene = []
                    this.scenes.forEach(ele => {
                        scene.push(ele.id)
                    })
                }
                let param = {advertiser_id: this.advertiser_id, action_scene: scene, action_days: this.day}
                if (this.hideTop) {
                    param['type'] = 'interest'
                } else {
                    param['type'] = 'action'
                }
                this.fullLoading = true
                this.$axios.get('/action/category', param).then(e => {
                    let data = e.data.data ? e.data.data : e.data
                    this.setItemType(data, CATEGORY)
                    this.categoryData = data
                    // this.groups.push(0)
                    // console.log("categoryData", this.categoryData)
                    this.makeCategoryList(0, this.categoryData)
                    // console.log('this.categoryList', this.categoryList)
                    this.setDefault()
                    this.fullLoading = false
                })
            },
            setDefault() {
                this.actionObj.categories.forEach(ele => {
                    if (this.selected.findIndex(e => e.id == ele.id) == -1) {
                        this.selected.push(ele)
                    }
                })
                this.actionObj.words.forEach(ele => {
                    if (this.selected.findIndex(e => ele instanceof Object && e.id == ele.id) == -1) {
                        this.selected.push(ele)
                    }
                })
            },
            setItemType(data, type) {
                data.forEach(ele => {
                    ele['type'] = type
                    if (ele.children) {
                        this.setItemType(ele.children, type)
                    }
                })
            },
            changeWhere() {
                this.loadData()
                this.$handleSelect()
            },
            isIndeterminate(data) {
                if (!data) {
                    return false
                }
                let checked = false
                let unchecked = false
                // console.log(this.selected)
                // let data = this.getTopSelects('类目词')
                for (let i = 0; i < data.length; i++) {
                    if (this.selected.findIndex(e => e == data[i].id) == -1) {
                        unchecked = true
                    } else {
                        checked = true
                    }
                }
                return checked && unchecked
            },
            makeCategoryList(pid, data) {
                data.forEach(ele => {
                    this.categoryList.push({id: ele.id, name: ele.name, num: ele.num, parent: pid, type: CATEGORY})
                    if (ele.children && ele.children.length > 0) {
                        this.makeCategoryList(ele.id, ele.children)
                    }
                })
            },
            getTopSelects(type) {
                let ret = []
                this.selected.forEach(ele => {
                    if (ele.type == KEYWORD && (type == ele.type || type == '')) {
                        ret.push(ele)
                        return
                    }
                    // if (ele  instanceof Object) {
                    //     if (type != '类目词') {
                    //         ret.push(ele)
                    //     }
                    //     return
                    // }
                    let obj = this.categoryList.find(e => {
                        return ele.id == e.id
                    })
                    if (obj) {
                        // 判断obj的parent是不是存在了
                        if (obj.parent > 0) {
                            let idx = this.selected.findIndex(e2 => {
                                return e2.id == obj.parent
                            })
                            if (idx != -1) {
                                return
                            }
                        }
                        if (type == ele.type || type == '') {
                            ret.push(obj)
                        }
                    }
                })
                return ret
                // data.forEach(e => {
                //     if (this.selected.indexOf(e.id) > -1) {
                //         // 找到
                //         ret.push(e)
                //     } else if (e.children) {
                //         this.getTopSelects(ret, e.children)
                //     }
                // })
            },
            selectCate(event, cate, notNotify) {
                // console.log('select')
                let idx = this.selected.findIndex( e2 => e2.id == cate.id && e2.type == CATEGORY)
                if (event && idx == -1) {
                    this.selected.push(cate)
                } else if(!event && idx > -1) {
                    this.selected.splice(idx, 1)
                }
                cate = this.getCategory(cate.id)
                // 对所有子节点也进行选择操作
                this.deepSelect(cate, event)
                // 进行上级查找，是否需要对父级数据进行选择操作
                let parent = []
                this.getCategoryParent(cate.id, parent)
                for (let i = 0; i < parent.length; i++) {
                    const ele = parent[i];
                    if (ele.children) {
                        let idx = ele.children.findIndex(e => {
                            return this.selected.findIndex( e2 => e2.id == e.id && e2.type == CATEGORY) == -1
                        })
                        let ii = this.selected.findIndex( e2 => e2.id == ele.id && e2.type == CATEGORY)
                        // 父级下有未选中项
                        if (idx != -1) {
                            // 父级却是选中状态,进行去除操作
                            if (ii > -1) {
                                this.selected.splice(ii, 1)
                            }
                        } else {
                            // 父级下都是选中项
                            if (ii == -1) {
                                // 添加上父级
                                this.selected.push(ele)
                            }
                        }
                    }
                }
                if (!notNotify) {
                    this.$handleSelect()
                }
                // console.log('setselect method selected', this.selected)
            },
            deepSelect(cate, event) {
                if (cate == null) {
                    return
                }
                if (cate.children) {
                    cate.children.forEach(e => {
                        let idx = this.selected.findIndex( e2 => e2.id == e.id && e2.type == CATEGORY)
                        if (event && idx == -1) {
                            this.selected.push(e)
                        } else if (!event && idx > -1) {
                            this.selected.splice(idx, 1)
                        }
                        this.deepSelect(e, event)
                    })
                }
            },
            getName(i) {
                if (i == 1) {
                    return '行为类目词'
                }
                let cate = this.getCategory(this.groups[i - 1])
                if (!cate) {
                    console.error('没有找到行为词', i)
                    return 'Error'
                }
                return cate.name
            },
            selectAll(i, event) {
                console.log('select all', i)
                if (i == 1) {
                    // 第一层直接处理
                    this.categoryData.forEach(e => {
                        this.selectCate(event, e, i, true)
                        let idx = this.selected.findIndex( e2 => e2.id == e.id && e2.type == CATEGORY)
                        if (event && idx == -1) {
                            this.selected.push(e)
                        } else if (!event && idx > -1) {
                            this.selected.splice(idx, 1)
                        }
                    })
                    this.$handleSelect()
                    return
                }
                let cate = this.getCategory(this.groups[i - 1])
                if (cate.children) {
                    cate.children.forEach(e => {
                        this.selectCate(event, e, i, true)
                        let idx = this.selected.findIndex( e2 => e2.id == e.id && e2.type == CATEGORY)
                        if (event && idx == -1) {
                            this.selected.push(e)
                        } else if (!event && idx > -1) {
                            this.selected.splice(idx, 1)
                        }
                    })
                }
                this.$handleSelect()
            },
            getCategoryParent(id, ret, data) {
                if (data == null) {
                    data = this.categoryData
                }
                for (let i = 0; i < data.length; i++) {
                    const e = data[i];
                    if (e.id == id) {
                        ret.push(e)
                        return true
                    }
                    if (e.children) {
                        let a = this.getCategoryParent(id, ret, e.children)
                        if (a) {
                            ret.push(e)
                            return true
                        }
                    }
                }
                return null
            },
            getCategory(id, data) {
                if (data == null) {
                    data = this.categoryData
                }
                for (let i = 0; i < data.length; i++) {
                    const e = data[i];
                    if (e.id == id) {
                        return e
                    }
                    if (e.children) {
                        let a = this.getCategory(id, e.children)
                        if (a) {
                            return a
                        }
                    }
                }
                return null
            },
            clickCategory(level, id) {
                let data = this.getCategory(id)
                // console.log('data', data)
                
                if (data.children) {
                    if (this.groups.length > level) {
                        this.groups.splice(level, this.groups.length - level)
                    }
                    this.groups.push(id)
                    this.$nextTick(() => {
                        this.$el.querySelector('#scrollBox').scrollLeft = this.$el.querySelector('#scrollBox').scrollWidth // - this.$refs.box.clientWidth
                        // console.log('this.$refs.scrollBox', this.$refs.scrollBox)
                        // document.getElementById('scrollBox').scrollLeft = 200
                    })
                } else {
                    console.log('没有下一级了')
                }

            },
            del(item) {
                if (item.type == KEYWORD) {
                    let idx = this.selected.findIndex(ele => {
                        return ele instanceof Object && ele.id == item.id
                    })
                    if (idx != -1) {
                        this.selected.splice(idx, 1)
                    }
                } else {
                    this.selectCate(false, item, 0)
                }
                this.$handleSelect()
            },
            keywordSearch(id, callback) {
                this.cutlogic = 2
                
                this.loading = true
                //
                // this.keywordTitle = this.getName(id)
                let cate = this.getCategory(id)
                console.log('cate', cate)
                this.keywordTitle = cate.name
                let scene = this.scene
                if (scene.length == 0) {
                    scene = []
                    this.scenes.forEach(ele => {
                        scene.push(ele.id)
                    })
                }
                let param = {advertiser_id: this.advertiser_id,
                    action_scene: scene,
                    action_days: this.day,
                    tag_type: cate.type,
                    targeting_type: this.actionObj.targeting_type,
                    id: id
                    }

                this.$axios.get('/action/keyword', param).then(e => {
                    // console.log('e,', e)
                    this.loading = false
                    e.data.keywords.forEach(ele => {
                        ele['type'] = 'KEYWORD'
                    })
                    if (callback) {
                        callback(e.data.keywords)
                    } else {
                        this.keywords = e.data.keywords
                    }
                }).catch(() => {
                    this.loading = false
                })
            },
            deepSearch(ret, keyword, data) {
                if (data == null) {
                    data = this.categoryData
                }
                for (let i = 0; i < data.length; i++) {
                    const e = data[i];
                    if (e.name.indexOf(keyword) != -1) {
                        ret.push(e)
                    }
                    if (e.children) {
                        this.deepSearch(ret, keyword, e.children)
                    }
                }
            },
            querySearch(queryString, cb) {
                var results = []
                this.deepSearch(results, queryString)
                console.log('results', results)
                // 调用 callback 返回建议列表的数据
                cb(results);
            },
            querySearch2(queryString, cb) {
                this.keywordSearch(queryString, function (results) {
                    cb(results)
                })
            },
            addKeyword(item) {
                // console.log('addKeyword', item)
                let idx = this.selected.findIndex(ele => {
                    // if (ele instanceof Object)
                    return ele instanceof Object && ele.id == item.id
                })
                if (idx == -1) {
                    this.selected.push(item) //'key' + item.id)
                    this.$handleSelect()
                }
            },
            handleSelect(item) {
                console.log(item);
                this.selectCate(true, item, 0)
            },
            handleIconClick(ev) {
                console.log(ev);
            },
            clear() {
                this.selected = []
            },
            handleDropdown(command) {
                if (command == 1) {
                    this.dropdownTitle = '类目词'
                    this.dropdownType = CATEGORY
                } else if (command == 2) {
                    this.dropdownTitle = '关键词'
                    this.dropdownType = KEYWORD
                } else {
                    this.dropdownTitle = '全部'
                    this.dropdownType = ''
                }
                // this.$message('click on item ' + command);
            },
            //当批量选中结束调用
            $handleSelect(){
                let actionObj = {
                    scene: this.scene,
                    days: this.day,
                    categories: this.getTopSelects(CATEGORY),
                    words: this.getTopSelects(KEYWORD)
                }
                this.$emit('change', actionObj)
            },
        }
    }
</script>

<style lang="scss">
     .feature_wrap .select-panel-left{
         min-width: 200px;
         max-width: 100%;
     }
    .feature_wrap .select-panel-left .check_contact {
        width: 100%;
        font-size: 14px;
    }

    .feature_wrap .select-panel-left .check_contact .el-button {
        width: 100%;
        padding: 0;
        color: #606266;
    }

    .feature_wrap .select-panel-left .check_contact .el-button span {
        width: 100%;
        text-indent: 8px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .feature_wrap .select-panel-left .check_none .el-checkbox__label {
    display: none;
}
.feature_wrap .inline-input{
    width: 410px;
}
    .my-autocomplete {
        li {
            line-height: normal;
            padding: 7px;

            .name {
                text-overflow: ellipsis;
                overflow: hidden;
            }

            .addr {
                font-size: 12px;
                color: #b4b4b4;
            }

            .highlighted .addr {
                color: #ddd;
            }
        }
    }
</style>